import time # todo：导入了时间模块
from httprunner import HttpRunner, Config, Step, RunTestCase, RunRequest # todo：引入了httprunner框架
from business.login.login_test_service import TestCaseCmord as GetToken # todo：引入登录
def get_base_url(): # todo：获取全局的url
    from common import config_reader
    return config_reader.ConfigReader('../common/base_config.cfg').get_config('backend_url')
class APIRequestConstructor(HttpRunner):  # todo：创建基础类，便于后面清除hrun的token信息和读取token信息
    config = (
        Config("API测试执行")
            .base_url(get_base_url())  # todo:    http://60.205.190.66:8899/
            .verify(False)) #  todo：忽略HTTPS的警告
    teststeps = [
        Step(
            RunTestCase("通过登录API获取token") # todo：call的时候用RunTestCase
                .call(GetToken) #
                .export(*["token", ]))]

class perform_requests():
    headers = {
        "Host": "60.205.190.66:8899",
        "Accept": "application/json, text/plain, */*",
        "Authori-zation": "Bearer " + "$token",  # todo： 将取出来的token拿到依赖接口使用
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36",
        "Referer": "http://60.205.190.66:8899/admin/product/product_list",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cookie": "think_lang=zh-cn; PHPSESSID=bef660c259ca1b16b852005082b5a394; WS_ADMIN_URL=ws://60.205.190.66:8899/notice; WS_CHAT_URL=ws://139.159.233.129:8899/msg; collapsed=false; uuid=1; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIxMzkuMTU5LjIzMy4xMjk6ODg5OSIsImF1ZCI6IjEzOS4xNTkuMjMzLjEyOTo4ODk5IiwiaWF0IjoxNjQ4MjIxMzk1LCJuYmYiOjE2NDgyMjEzOTUsImV4cCI6MTY1MDgxMzM5NSwianRpIjp7ImlkIjoxLCJ0eXBlIjoiYWRtaW4ifX0.89SVNeMjXZ-j9KCiOjXwpq0aYgwZIonjI6LOkfUBhDE; expires_time=1650813395",
        "Connection": "keep-alive",
    }
    cookies = {"aaf875be9aad4feca52ccece8eade2df": "WyIxNjUxMTM1OTE1Il0"}  # todo：根据项目需要，写入cookies数据
    def reset_request_step(self,token=GetToken) :  # todo：基于类封装方法，默认不传则使用GetToken
        APIRequestConstructor.teststeps.clear()  # todo：属于单元测试框架内的teardown，给每个用例一个干净的执行环境
        APIRequestConstructor.teststeps.append(  # todo：添加step动作
            Step(
                RunTestCase("通过登录API获取token")
                    .call(token)
                    .export(*["token", ])
            ))
    def create_run_request(self,math,request_name, url, request_json=None, body="body.data", headers=headers,
                           cookies=cookies):  # todo：封装用例步骤，放置API的名字、请求地址、请求参数
        if math == 'post' or math=='POST':  # todo：如果请求参数json格式不为空，则执行post请求
            return RunRequest(request_name).post(url).with_headers(**headers).with_cookies(**cookies).with_json(
                request_json
            ).extract().with_jmespath(body, "res_data")
        elif math == 'get' or math =='GET':  # todo：如果请求参数json为空，则执行post请求
            return RunRequest(request_name).get(url).with_headers(**headers).with_cookies(**cookies) \
                .extract().with_jmespath(body, "res_data")
        elif math=='delete' or math=='DELETE':
            return RunRequest(request_name).delete(url).with_headers(**headers).with_cookies(**cookies) \
                .extract().with_jmespath(body, "res_data")

    def contruct_request_step(self,run_request_obj):
        return Step(
            run_request_obj
        )
    def perform_requests_and_get_last_response(self,steps):  # todo： 放入用例的执行步骤
        APIRequestConstructor.teststeps.extend(steps)  # todo：读取teststeps的步骤
        obj = APIRequestConstructor()  # todo：实例化对象
        obj.test_start()
        time.sleep(1)
        res = obj.with_export(["res_data", "token"]).get_export_variables()
        return res   # todo：方便我们后面提取参数
